
package session02;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLFilterImpl;
import org.xml.sax.helpers.XMLReaderFactory;


public class Session2 {

    public static void main(String[] args) {
        try {
//            SAXParserFactory factory = SAXParserFactory.newInstance();
//            SAXParser parser = factory.newSAXParser();
//            parser.parse(new File("shiporder.xml"), new ShipOrderHandler());
            //Khoi tao bien goi ham Filter
            ShipOrderTitleFilter filter = new ShipOrderTitleFilter();
            //Khoi tao doi tuong XMLReader
            XMLReader reader = XMLReaderFactory.createXMLReader();
            //Set lop-cha cho filter la reader
            filter.setParent(reader);
            //Set ham xu ly noi dung
            filter.setContentHandler(new ShiperOrderHandler());
            //Chi dinh duong dan doc file
            filter.parse(new InputSource(new FileInputStream("shiporder.xml")));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

//Ham Filter de loc ra title
 class ShipOrderTitleFilter extends XMLFilterImpl {
    private boolean itemFound = true;

    @Override
    public void startElement(String uri, String localName, String qName, Attributes atts)throws SAXException{
        if(qName.equals("title")){
            itemFound = true;
            super.startElement(uri, localName, qName,atts);
        }
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException{
        if(itemFound){
            //Khoi tao mang char Upper theo chieu dai mang
            char[] upperChar = new char[ch.length];
            for (int i = 0; i < ch.length; i++) {
                upperChar[i] = Character.toUpperCase(ch[i]);
            }
            itemFound = false;
            super.characters(upperChar, start, length);
        }
    }
}

 class ShiperOrderHandler extends DefaultHandler{
    private boolean itemFound = false;

    @Override
    public void startElement(String uri, String localName, String qName, Attributes atts)throws SAXException{
        if(qName.equals("title")){
            itemFound = true;
        }
    }

    @Override
    public void characters(char[] ch, int start, int length)throws SAXException{
        if(itemFound){
            //In ra chuoi ky tu bat dau tu start xac dinh theo chieu dai
            System.out.println(new String(ch, start,length));
            itemFound = false;
        }
    }
 }
